package com.ray.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import com.google.apphosting.api.search.AclPb.Entry.Permission;
import com.google.gson.Gson;
import com.ray.bean.UserBean;
import com.ray.bean.WeiXinPeopleBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.UserMapper;
import com.ray.pojo.ClockSend;
import com.ray.pojo.Department;
import com.ray.pojo.MyUser;
import com.ray.pojo.User;
import com.ray.util.TimeAndUnix;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.WeiXinUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



@Service
public class WeiXinService {
	
    //获取打卡数据路径
	private static String getClockUrl="https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=ACCESS_TOKEN";
	//获取权限签名路径
	private static String getTiketUrl="https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=ACCESS_TOKEN";
	//获取权限签名路径
	private static String getUserDetilUrl="https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=";
	//获取微信公众号用户信息的url
	private static String getWeiXinPublicNumberUser="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
	
	@Autowired
	Contacts_UserService contacts_UserService;
	@Autowired
	Contacts_DepartmentService contacts_DepartmentService;
	@Autowired
	UserService userService;
	@Autowired 
	UserMapper userMapper;
	@Autowired
	DepartmentService departmentService;
	@Autowired
	WeiXinPeopleService weiXinPeopleService;
	@Autowired
	PermissionService permissionService;
	@Autowired
    BasicDataService basicDataService;
	
	//将前台选中的人添加到微信接受人表中
	public void addSend(String stringId) {
		JSONArray jsonArray = JSONArray.fromObject(stringId);
		List<String> peopleIdList=jsonArray.subList(0, jsonArray.size());
		String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpID, WeiXinParamesUtil.workSecret).getToken();
	    List<User> userList=new ArrayList();
		User user=null;
		for(int i=0;i<peopleIdList.size();i++) {
			user=new User();
			JSONObject jsonUser=contacts_UserService.getUser(accessToken, peopleIdList.get(i));
			user.setDepartment(jsonUser.getString("department"));
			user.setEmail(jsonUser.getString("email"));
			user.setGender(jsonUser.getString("gender"));
			user.setMobile(jsonUser.getString("mobile"));
			user.setName(jsonUser.getString("name"));
			user.setPosition(jsonUser.getString("position"));
			user.setUserid(jsonUser.getString("userid"));
			userList.add(user);
		}
		userMapper.addSend(userList);
	}

	public List<User> getSendPeople(String dapartmentId) {
		return userMapper.getSendPeople(dapartmentId);
	}

	public String getTouser() {
		String touser="";
		List<User> userList=this.getSendPeople("");
		for(User user:userList) {
			touser+=user.getUserid()+"|";
		}
		return touser;
	}

	//获取微信打卡记录
	public Map getClock() {
		ClockSend clockSend=new ClockSend();
		clockSend.setOpencheckindatatype(3);
		String yesterdayStart=TimeAndUnix.getBeforeDay(0," 00:00:00");
		String yesterdayEnd=TimeAndUnix.getBeforeDay(0," 23:59:59");
		clockSend.setStarttime(TimeAndUnix.Date2TimeStamp(yesterdayStart, "yyyy-MM-dd HH:mm:ss"));
		clockSend.setEndtime(TimeAndUnix.Date2TimeStamp(yesterdayEnd, "yyyy-MM-dd HH:mm:ss"));
		String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpID, WeiXinParamesUtil.addressSecret).getToken();
		JSONObject jSONObject =contacts_UserService.getDepartmentUser(accessToken, "1", "1");
		String jsonUser=jSONObject.getString("userlist");
		JSONArray jsonArray = JSONArray.fromObject(jsonUser);
		List<String> userList=new ArrayList();
		if(jsonArray.size()>0) {
			for(int i=0;i<jsonArray.size();i++) {
				JSONObject json=jsonArray.getJSONObject(i);
				userList.add(json.getString("userid"));
			}
		}
		clockSend.setUseridlist(userList);
		Gson gson = new Gson(); 
	    String jsonClock =gson.toJson(clockSend);
	    accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpID, WeiXinParamesUtil.dakaSecret).getToken();
	    String url =getClockUrl.replace("ACCESS_TOKEN", accessToken);
	    JSONObject daKaJsonObject = WeiXinUtil.httpRequest(url, "POST", jsonClock);  
        Set<String> errorSet=new HashSet<String>();
        Set<String> allSet=new HashSet<String>();
        System.out.println("jsonObject:"+daKaJsonObject.toString());
        String jsonResult=daKaJsonObject.getString("checkindata");
		JSONArray resultArray = JSONArray.fromObject(jsonResult);
		if(resultArray.size()>0) {
			for(int i=0;i<resultArray.size();i++) {
				JSONObject json=resultArray.getJSONObject(i);
				String exception=json.getString("exception_type");
				if(!"".equals(exception)) {
					errorSet.add(json.getString("userid"));
				}
				allSet.add(json.getString("userid"));
			}
		}
	    
	    System.out.println("需打卡人数"+allSet.size()+"   :    打卡异常人数"+errorSet.size());
		Map<String,Integer> succAndErrMap=new HashMap<String,Integer>();
		succAndErrMap.put("successUserCount", allSet.size()-errorSet.size());
		succAndErrMap.put("errorUserCount", errorSet.size());
	    return succAndErrMap;
	}

	//获取微信sdk借口配置参数
	public Map getConfig(String ticken,String userName,String url) throws UnsupportedEncodingException {
		Map<String,String> map=new HashMap<String,String>();
		String noncestr=TimeAndUnix.create_nonce_str();
		String timestamp=TimeAndUnix.getNowTimeStamp();
		String signature=WeiXinUtil.getJsSdkSign(noncestr, ticken, timestamp, url);
		System.out.println("ticken:"+ticken);
		System.out.println("noncestr:"+noncestr);
		System.out.println("timestamp:"+timestamp);
		System.out.println("url:"+url);
		System.out.println("signature:"+signature);
		map.put("appId", WeiXinParamesUtil.corpID);//appId
		map.put("timestamp", timestamp);//时间戳
		map.put("nonceStr", noncestr);//随机字符串
		map.put("signature", signature);//随机字符串
		return map;
	}
	
	//获取签名
	public String getSignature() {
		String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpID, WeiXinParamesUtil.workSecret).getToken();
		return null;
	}

	 //根据user_ticket获取微信用户信息
	public UserBean getUserByUser_ticket(String user_ticket) {
		UserBean userBean=new UserBean();
		Map<String,String> map=new HashMap<String,String>();
		map.put("user_ticket", user_ticket);
		JSONObject json=JSONObject.fromObject(map);
		String token=WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpID, WeiXinParamesUtil.workSecret).getToken();
		String url=getUserDetilUrl+token;
		JSONObject daKaJsonObject = WeiXinUtil.httpRequest(url, "POST", json.toString());
		System.out.println(daKaJsonObject);
		String userId=daKaJsonObject.getString("userid");
		String name=daKaJsonObject.getString("name");
//		String mobile=daKaJsonObject.getString("phone");
		String avatar=daKaJsonObject.getString("avatar");
		userBean.setUserName(name);
		userBean.setUserCard(name);
		userBean.setWeiXinId(userId);
		userBean.setPassword("123");
		userBean.setCompany(WeiXinParamesUtil.company);
		userBean.setStatus("开启");
//		userBean.setPhone(mobile);
		userBean.setAvatar(avatar);
		userService.insertUser(userBean);
		return userBean;
	}

	//获取报工人员
	public String getDelayWorkUser(String code, HttpServletRequest request) throws ServiceException {
		String token=WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpID, WeiXinParamesUtil.workSecret).getToken();
		String url=WeiXinUtil.getCodeToUserUrl(token, code);
		String object=WeiXinUtil.httpRequest(url);
		JSONObject jsonObject=JSONObject.fromObject(object);
		String weiXinUserId=jsonObject.getString("UserId");
		System.out.println("微信用户id："+weiXinUserId);
		UserBean userBean=userService.getUserByWeiXinId(weiXinUserId);
		if(null==userBean) {
			String user_ticket=jsonObject.getString("user_ticket");
			userBean=this.getUserByUser_ticket(user_ticket);
		}
		userBean=userService.getUserBean(userBean);
		MyUser myUser=new MyUser();
		System.out.println("企业微信报工获取的用户id");
		myUser.setUserId(userBean.getId());
		myUser=userService.getUser(myUser);
		if(myUser==null) {
			throw new ServiceException("此账号不存在，或被禁用！");
		}
		request.getSession().setAttribute("userLogin", myUser);
		return userBean.getUserName();
	}
	
	/**
	 * 获取微信openID
	 * @param code
	 * @return
	 */
	public JSONObject getOpenId(String code) {
		String url=WeiXinUtil.getWeiXinPublicNumberCodeToUserUrl(code);
		String object=WeiXinUtil.httpRequest(url);
		JSONObject jsonObject=JSONObject.fromObject(object);
		String openid=jsonObject.getString("openid");
		String token=this.getAccessToken(null);
		String getUserUrl=getWeiXinPublicNumberUser.replace("ACCESS_TOKEN", token).replace("OPENID", openid);
		String userString=WeiXinUtil.httpRequest(getUserUrl);
		System.out.println(getUserUrl);
		System.out.println(userString);
		JSONObject userObject=JSONObject.fromObject(userString);
		return  userObject;
	}
	
	
	//获取为您公众号报工人员
	public MyUser getWeiXinPublicNumberReportUser(String code,HttpServletRequest request, String company,String redirUrl) throws ServiceException, IOException {
		String returnName="";
		String url=WeiXinUtil.getWeiXinPublicNumberCodeToUserUrl(code);
		System.out.println(url);
		String object=WeiXinUtil.httpRequest(url);
		System.out.println(object);
		JSONObject jsonObject=JSONObject.fromObject(object);
		String openid=jsonObject.getString("openid");
		
		List<WeiXinPeopleBean> weiXinPeopleList=weiXinPeopleService.getWeiXinPeopleByOpenId(openid);
		weiXinPeopleList=weiXinPeopleList==null?new ArrayList<WeiXinPeopleBean>():weiXinPeopleList;
		if(weiXinPeopleList.size()>1) {
			if(company!= null && !"".equals(company)) {
				weiXinPeopleList=weiXinPeopleList.stream().filter(ww->company.equals(ww.getCompany())).collect(Collectors.toList());
			}
			if(weiXinPeopleList.size()>1) {
				JSONArray jsonArray=new JSONArray();
	    		for(WeiXinPeopleBean mm:weiXinPeopleList) {
	    			net.sf.json.JSONObject object2=new net.sf.json.JSONObject();
	    			object2.put("openid", mm.getOpenid());
	    			object2.put("company", mm.getCompany());
	    			jsonArray.add(object2);
	    		}
				String string=jsonArray.toString();
	    		string=URLEncoder.encode(string,"UTF-8");
	    		string="/phoneApp/companySelect?userStr="+string+"&url="+redirUrl;
	    		Assert.isTrue(false,"重定向错误"+string);
			}
		}
		
//		MyUser myuser=(MyUser) request.getSession().getAttribute("userLogin");
		MyUser myUser=new MyUser();
		String token=this.getAccessToken(request);
		String getUserUrl=getWeiXinPublicNumberUser.replace("ACCESS_TOKEN", token).replace("OPENID", openid);
		String userString=WeiXinUtil.httpRequest(getUserUrl);
		System.out.println(getUserUrl);
		System.out.println(userString);
		JSONObject userObject=JSONObject.fromObject(userString);
		WeiXinPeopleBean wxpb = (WeiXinPeopleBean)JSONObject.toBean(userObject,WeiXinPeopleBean.class);
		//如果第一次获取用户信息
		if(weiXinPeopleList.size()<=0) {
			if(wxpb.getOpenid()==null || wxpb.getOpenid().equals("")) {
				wxpb.setOpenid(openid);
			}
//			if(null!=myuser) {
//				wxpb.setUserId(myuser.getUserId());
//				returnName=myuser.getUserName();
//			}
			wxpb.setCompany(company);
			weiXinPeopleService.insertWeiXinPeople(wxpb);
		}else {
			weiXinPeopleService.updateWeiXinPeople(wxpb);
			WeiXinPeopleBean weiXinPeople=weiXinPeopleList.get(0);
			String userId=weiXinPeople.getUserId();
			//如果用户微信用户没有和系统用户关联，并且用户已登录，关联用户
			if(null==userId||"".equals(userId)) {
//				if(null!=myuser) {
//					weiXinPeople.setUserId(myuser.getUserId());
//					returnName=myuser.getUserName();
//				}
			}else {//用户id不为空
//				if(null==myuser) {
					MyUser mm=new MyUser();
					mm.setUserId(userId);
					myUser=userService.getUserByUserId(mm);
					if(myUser!=null) {//如果用户还还存在没有被禁用
						myUser.setPermissionList(permissionService.getUserPermissionBeanByUserId(myUser.getUserId()));
						myUser.setCompanyInfo(userService.getCompanyInfo(myUser.getCompany()));
						/**
						 * 取消 在查用户的时候添加了公司id nate
				         * 添加公司表公司id ssg
				         */
//				        myUser.setCompanyId(basicDataService.getCompanyId(myUser.getCompany()));
						request.getSession().setAttribute("userLogin", myUser);
						returnName=myUser.getUserName();
					}else {
						weiXinPeopleService.removeBindByOpenId(openid);
					}
					
			}
		}
		MyUser returnUser=new MyUser();
		returnUser.setUserName(returnName);
		returnUser.setWeiXinPublicOpenId(openid);
		returnUser.setUnionId(userObject.has("unionid")?userObject.getString("unionid"):"");
		return returnUser;
	}
	
	
	
	//获取微信公众号全局accesstoken
	public String getAccessToken(HttpServletRequest request) throws ServiceException {
		String accessToken=userMapper.getAccessToken();
		//如果没有
		if(null==accessToken || "".equals(accessToken)) {
			accessToken=WeiXinUtil.getAccessToken();
			userMapper.insertAccessToken(accessToken,"轩昊科技");
		}
		return accessToken;
	}
//	//获取微信公众号全局accesstoken
//	public String getAccessToken(HttpServletRequest request) throws ServiceException {
//		Object accessTokenTime=request.getSession().getAttribute("AccessTokenTime");
//		Long beforeTime=(long) 0;
//		String accessToken=(String) request.getSession().getAttribute("AccessToken");
//		if(null!=accessTokenTime) {
//			beforeTime=(Long)accessTokenTime;
//		}
//		long jianGe=(System.currentTimeMillis()-beforeTime)/3600000;
//		//如果大于一小时就重新获取
//		if(jianGe>1) {
//			accessToken=WeiXinUtil.getAccessToken();
//			request.getSession().setAttribute("AccessTokenTime", System.currentTimeMillis());
//			request.getSession().setAttribute("AccessToken", accessToken);
//		}
//		return accessToken;
//	}
	
	
	
	//获取微信部门并增加到数据库
	public void setDept() {
		 String departmentId="0";
		 String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpID, WeiXinParamesUtil.workSecret).getToken();//获取token
	     JSONObject xx=contacts_DepartmentService.getDepartmentList(accessToken, departmentId);//获取部门json字符串
	     String deptStr=xx.getString("department");
	     System.out.println(deptStr);
	     JSONArray jsonArray = JSONArray.fromObject(deptStr);//把String转换为 数组 
	     List<Department> list= (List<Department>)JSONArray.toCollection(jsonArray, Department.class);//jsonarray转换为对象数组
		 for(Department dd:list) {//遍历部门
			 Department department =departmentService.getDepartmentByWeiXin(dd);
			 if(null==department) {//如果数据库库中没有此部门，添加新部门
				 departmentService.insertDepartment(dd);
			 }else {//如果有判断部门名称是否相同
				 if(!department.getName().equals(dd.getName())) {
					 departmentService.updateDepartmrnt(dd);
				 }
			 }
		 }
	}

	public List<String> getUserWorkShop(String userName) throws ServiceException {
		String depe=userService.getDepartment(userName);
		 if(null==depe || "".equals(depe)) {
			 throw new ServiceException("您还没有分配部门(车间)");
		 }
		String[] deptId=depe.split(",");
		return departmentService.getDepartmentName(deptId);
	}

	//获取企业微信ticket
	public String getTiket(HttpServletRequest request) throws ServiceException {
		Object object=request.getSession().getAttribute("beforeTime");
		Long beforeTime=(long) 0;
		String ticket=(String) request.getSession().getAttribute("ticket");
		if(null!=object) {
			beforeTime=(Long)object;
		}
		Long jianGe=(System.currentTimeMillis()-beforeTime)/1000;
		if(jianGe>6000) {
			ticket=WeiXinUtil.getTicket();
			request.getSession().setAttribute("beforeTime", System.currentTimeMillis());
			request.getSession().setAttribute("ticket", ticket);
		}
		return ticket;
	}
	
	//获取微信sdk借口配置参数 微信公众号
	public Map getConfigJsSDK(String url) throws UnsupportedEncodingException {
		String accessToken=getAccessToken(null);
		String ticken=WeiXinUtil.getJsSDKTicket(accessToken);
		Map<String,String> map=new HashMap<String,String>();
		String noncestr=TimeAndUnix.create_nonce_str();
		String timestamp=TimeAndUnix.getNowTimeStamp();
		String signature=WeiXinUtil.getJsSdkSign(noncestr, ticken, timestamp, url);
		System.out.println("ticken:"+ticken);
		System.out.println("noncestr:"+noncestr);
		System.out.println("timestamp:"+timestamp);
		System.out.println("url:"+url);
		System.out.println("signature:"+signature);
		map.put("appId", WeiXinParamesUtil.weiXinPbulicNumberAppId);//appId
		map.put("timestamp", timestamp);//时间戳
		map.put("nonceStr", noncestr);//随机字符串
		map.put("signature", signature);//随机字符串
		System.out.println(map);
		return map;
	}

	

}
